from rest_framework import serializers
from goods.models import SKU
from .models import OrderGoods,OrderInfo

class CartGoodsSerializer(serializers.ModelSerializer):
    count = serializers.IntegerField(label='订单中该商品的数量')
    class Meta:
        model = SKU
        fields = ['id','name','price','default_image_url','count']


#查询订单列表用的三个序列化器嵌套
class OrderSKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['name','default_image_url','price','id']
class OrderGoodsSerializer(serializers.ModelSerializer):
    sku = OrderSKUSerializer(read_only=True)
    class Meta:
        model = OrderGoods
        fields = ['sku','count','price']
class OrderListSerializer(serializers.ModelSerializer):
    skus = OrderGoodsSerializer(many=True,read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S",read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['create_time','order_id','total_amount','freight','pay_method','status','skus']
        ordering = ['create_time']


class OrderIdSerializer(serializers.ModelSerializer):
    class Meta:
        model =OrderInfo
        fields = '__all__'

#保存订单评论的序列化器
class CommentOrderSerializer(serializers.ModelSerializer):
    score = serializers.IntegerField(max_value=5,min_value=1,label='商品评价')
    class Meta:
        model = OrderGoods
        fields = ['comment','score','is_anonymous','order','sku']

    def update(self, instance, validated_data):

        orderId = validated_data.get('order')
        comment = validated_data.get('comment')
        score = validated_data.get('score')
        is_anonymous = validated_data.get('is_anonymous')

        try:
            ret = instance.update(
                comment = comment,
                score = score,
                is_anonymous = is_anonymous,
                is_commented = True
            )
        except Exception:
            raise serializers.ValidationError('保存订单数据提交失败')

        if 0==ret:
            raise serializers.ValidationError('保存订单失败')

        try:
            count = OrderGoods.objects.filter(order=orderId.order_id,is_commented=False).count()
        except Exception:
            raise serializers.ValidationError('查询剩余待评价商品数据失败')
        if 0==count:
            try:
                OrderInfo.objects.filter(order_id=orderId.order_id).update(
                    status = OrderInfo.ORDER_STATUS_ENUM['FINISHED']
                )
            except Exception:
                raise serializers.ValidationError('保存订单评价状态失败')

        return validated_data

